package routers

import (
	"echo-utils/internal/dao"
	"echo-utils/internal/service"
	"echo-utils/pkg/app"
	"echo-utils/pkg/errcode"

	"github.com/gin-gonic/gin"
)

type SetPath struct {
	Path string `form:"path" json:"path" binding:"required"`
}

type DelPath struct {
	Id int64 `form:"id" json:"id" binding:"required"`
}

type ImportSource struct {
	Paths []string `form:"paths" json:"paths" binding:"required"`
}

type SystemApi struct{}

func NewSystemApi() *SystemApi {
	return &SystemApi{}
}

func (s *SystemApi) SetPath(c *gin.Context) {
	var sets SetPath
	if err := c.ShouldBindJSON(&sets); err != nil {
		app.NewResponse(c).ToErrorResponse(errcode.InvalidParams)
		return
	}
	ef := service.NewEchoFile()
	if !ef.IsDir(sets.Path) {
		app.NewResponse(c).ToErrorResponse(errcode.NotDir)
		return
	}
	dao := dao.NewSystemDao()
	list := dao.SetPath(sets.Path)
	app.NewResponse(c).ToSuccessResponse(list)
}

func (s *SystemApi) Paths(c *gin.Context) {
	dao := dao.NewSystemDao()
	list := dao.Paths()
	app.NewResponse(c).ToSuccessResponse(list)
}

func (s *SystemApi) DelPath(c *gin.Context) {
	var sets DelPath
	if err := c.ShouldBindJSON(&sets); err != nil {
		app.NewResponse(c).ToErrorResponse(errcode.InvalidParams)
		return
	}
	dao := dao.NewSystemDao()
	list := dao.DelPath(sets.Id)
	app.NewResponse(c).ToSuccessResponse(list)
}

func (s *SystemApi) ImportSource(c *gin.Context) {
	var paths ImportSource
	if err := c.ShouldBindJSON(&paths); err != nil {
		app.NewResponse(c).ToErrorResponse(errcode.InvalidParams)
		return
	}
	sr := service.NewSourceCore(paths.Paths)
	go sr.Scan()
	app.NewResponse(c).ToSuccessResponse("")
}

func (s *SystemApi) WorkerLogs(c *gin.Context) {
	ldao := dao.NewIlogDao()
	msg := ldao.List()
	app.NewResponse(c).ToSuccessResponse(msg)
}
